#include "StateManager.h"

#include <cassert>

#include <main/GameLoop.h>
#include <main/Globals.h>
#include <states/GameState.h>
#include <states/GameStates.h>

StateManager::StateManager()
    : mCurState(0)
    , mNewState(0)
{
    Globals::gGameLoop->updateMe(this);
}

StateManager::~StateManager() {
    Globals::gGameLoop->removeMe(this);

    mCurState = nullptr;
    mNewState = nullptr;
}

void StateManager::init() {
    // By default, we start with the introduction mode...
    changeState(*Globals::gGameStates->mLevel1State);
}

void StateManager::update() {
    // Update current state
    if (mCurState) {
        mCurState->update();
    }

    // If there is a new state
    // we should clear previous one
    // and init new one.
    // Current and previous state 
    // must be different
    if (mNewState) {
        if (mCurState) {
            mCurState->clear();
        }

        assert(mNewState != mCurState);
        mCurState = mNewState;
        mNewState = nullptr;

        mCurState->init();
    }
}

void StateManager::changeState(GameState &state) {
    assert(mNewState == nullptr);
    mNewState = &state;
}